package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.Student;
import org.example.config.JwtConfig;
import org.example.mapper.Usermapper;
import org.example.service.UserService;
import org.example.util.JsonResult;
import org.example.util.MD5Util;
import org.example.util.ResultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:Liu
 * @Testname:UserServiceImpl
 * @Date:2025/9/16 11:30
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<Usermapper, Student> implements UserService {

    private Usermapper studentMapper;
    private StringRedisTemplate stringRedisTemplate;
    private ValueOperations<String, String> valueOperations;

    @Autowired
    public UserServiceImpl(Usermapper studentMapper, StringRedisTemplate stringRedisTemplate) {
        this.studentMapper = studentMapper;
        this.stringRedisTemplate = stringRedisTemplate;
        valueOperations = stringRedisTemplate.opsForValue();
    }

    @Override
    public JsonResult login(Student user) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_no", user.getStuNo());
        wrapper.eq("password", MD5Util.encryptMD5(user.getPassword()));
        Student student = studentMapper.selectOne(wrapper);
        if (student == null) {
            return ResultTool.fail(201,"账号或密码错误");
        }
        String token = JwtConfig.getJwtToken(student);
        log.info("id:{}",student.getId());
        valueOperations.set("token:" + student.getId(), token,1, TimeUnit.DAYS);
        return ResultTool.success(token);
    }
}
